package com.zwcl.glass.tools.controller;


import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.exception.BusinessException;
import com.zwcl.common.core.validator.groups.Add;
import com.zwcl.common.core.validator.groups.Update;
import com.zwcl.glass.tools.entity.UserData;
import com.zwcl.glass.tools.entity.UserRelationship;
import com.zwcl.glass.tools.service.TestRecordService;
import com.zwcl.glass.tools.service.UserDataService;
import com.zwcl.glass.tools.service.UserRelationshipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xieyongping
 * @since 2021-03-03
 */
@RestController
@RequestMapping("/relationship")
public class UserRelationshipController {
    @Autowired
    private UserRelationshipService userRelationshipService;

    /**
     * 添加
     */
    @PostMapping("/add")
    public ApiResult<Integer> addRelationshipData(@Validated(Add.class) @RequestBody UserRelationship userData) throws Exception {
        Boolean existFlag = userRelationshipService.isExist(userData);
        if(existFlag){
            throw new BusinessException("已存在该用户的关系人");
        }
        Integer count =userRelationshipService.countUserRelationship(userData.getUserId(),userData.getRelationship());
        if(userData.getRelationship()<=1 && count>=1){
            throw new BusinessException("自己和妻子关系不能超过一人");
        }
        boolean flag = userRelationshipService.save(userData);
        if(!flag){
            throw new BusinessException("保存关系人失败");
        }
        return ApiResult.ok(userData.getId());
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public ApiResult<Boolean> updateRelationship(@Validated(Update.class) @RequestBody UserRelationship userData) throws Exception {
        boolean flag = userRelationshipService.updateById(userData);
        return ApiResult.result(flag);
    }

    /**
     * 删除
     */
    @PostMapping("/delete/{id}")
    public ApiResult<Boolean> deleteRelationship(@PathVariable("id") Integer id) throws Exception {
        boolean flag = userRelationshipService.deleteEntity(id);
        return ApiResult.result(flag);
    }

    @GetMapping("/list")
    public List<UserRelationship> listRelationship(@RequestParam Long userId){
        List<UserRelationship> userData = userRelationshipService.getUserRelationshipByUserId(userId);
        return userData;
    }
}

